package com.pony.iphone.controller;

import com.pony.iphone.properties.SshConfigProperties;
import com.pony.iphone.service.SshService;
import com.pony.iphone.utils.AppHttpCodeEnum;
import com.pony.iphone.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author pony
 * @date 2023/7/17
 */
@RestController
@RequestMapping("/ssh")
public class SshController {

    @Autowired
    private SshConfigProperties sshConfig;

    @Autowired
    private SshService sshService;

    /**
     * 通过 IP 查询系统日志
     */
    @GetMapping("/workerId/{ip}")
    public R searchSyslog(
            @PathVariable String ip) {

        Map<String, Object> response = new HashMap<>();

        try {
            // 1. 输入验证
            String cleanedIp = cleanAndValidateIp(ip);
            if (cleanedIp == null) {
                return R.error(AppHttpCodeEnum.ERROR)
                        .message("IP地址格式无效");
            }

            // 2. 执行查询
            String result = sshService.searchSyslogByIp(cleanedIp);
            List<Map<String, String>> parsedResults = parseLogResults(result, cleanedIp);

            response.put("searchIp", cleanedIp);
            response.put("results", parsedResults);
            response.put("totalCount", parsedResults.size());

            return R.success(AppHttpCodeEnum.SUCCESS)
                    .message("根据 ip 查询 workerId 成功！").data(response);

        } catch (Exception e) {
            return R.error(AppHttpCodeEnum.ERROR).message("查询失败，请稍后重试");
        }
    }

    /**
     * 清理和验证IP地址
     */
    private String cleanAndValidateIp(String ip) {
        if (ip == null) return null;

        // 去除所有空白字符
        String cleaned = ip.replaceAll("\\s+", "");

        // 验证IP格式
        if (!isValidIpAddress(cleaned)) {
            return null;
        }

        return cleaned;
    }

    /**
     * 解析日志结果，提取时间和worker信息
     */
    private List<Map<String, String>> parseLogResults(String logContent, String searchIp) {
        List<Map<String, String>> results = new ArrayList<>();
        
        if (logContent == null || logContent.trim().isEmpty() || 
            logContent.contains("No matching entries") || 
            logContent.contains("No results found")) {
            return results;
        }
        
        // 按行分割日志
        String[] lines = logContent.split("\n");
        
        for (String line : lines) {
            if (line.trim().isEmpty()) continue;
            
            Map<String, String> logEntry = parseLogLine(line, searchIp);
            if (logEntry != null && !logEntry.isEmpty()) {
                results.add(logEntry);
            }
        }
        
        return results;
    }

    /**
     * 解析单行日志，提取时间和worker
     */
    private Map<String, String> parseLogLine(String line, String searchIp) {
        try {
            Map<String, String> result = new HashMap<>();
            
            // 如果行包含 "No results found" 或类似信息，跳过解析
            if (line.contains("No results found") || line.contains("No matching entries")) {
                return result;
            }
            
            // 提取时间部分 (Nov 22 22:01:39)
            String timePart = extractTime(line);
            if (timePart != null) {
                result.put("timestamp", timePart);
            }
            
            // 提取worker ID
            String workerId = extractWorkerId(line);
            if (workerId != null) {
                result.put("workerId", workerId);
            }
            
            // 提取任务ID
            String taskId = extractTaskId(line);
            if (taskId != null) {
                result.put("taskId", taskId);
            }
            
            // 提取脚本信息
            String script = extractScript(line);
            if (script != null) {
                result.put("script", script);
            }
            
            // 提取完整日期时间（如果有）
            String fullDateTime = extractFullDateTime(line);
            if (fullDateTime != null) {
                result.put("fullDateTime", fullDateTime);
            }
            
            // 添加原始日志行（用于调试）
            result.put("rawLog", line);
            result.put("searchedIp", searchIp);
            
            return result;
            
        } catch (Exception e) {
            // 如果解析失败，返回基础信息
            Map<String, String> fallback = new HashMap<>();
            fallback.put("rawLog", line);
            fallback.put("searchedIp", searchIp);
            fallback.put("error", "解析失败: " + e.getMessage());
            return fallback;
        }
    }

    /**
     * 提取时间信息 (Nov 22 22:01:39)
     */
    private String extractTime(String line) {
        // 匹配类似 "Nov 22 22:01:39" 的时间格式
        java.util.regex.Pattern timePattern = java.util.regex.Pattern.compile(
            "([A-Za-z]{3}\\s+\\d{1,2}\\s+\\d{2}:\\d{2}:\\d{2})"
        );
        java.util.regex.Matcher matcher = timePattern.matcher(line);
        if (matcher.find()) {
            return matcher.group(1).trim();
        }
        return null;
    }

    /**
     * 提取完整日期时间 (2025-11-22 22:01:39.504)
     */
    private String extractFullDateTime(String line) {
        // 匹配类似 "2025-11-22 22:01:39.504" 的完整日期时间格式
        java.util.regex.Pattern dateTimePattern = java.util.regex.Pattern.compile(
            "(\\d{4}-\\d{2}-\\d{2}\\s+\\d{2}:\\d{2}:\\d{2}\\.\\d{3})"
        );
        java.util.regex.Matcher matcher = dateTimePattern.matcher(line);
        if (matcher.find()) {
            return matcher.group(1).trim();
        }
        return null;
    }

    /**
     * 提取worker ID
     */
    private String extractWorkerId(String line) {
        // 匹配 worker:007 格式
        java.util.regex.Pattern workerPattern = java.util.regex.Pattern.compile(
            "worker:([a-zA-Z0-9-]+)"
        );
        java.util.regex.Matcher matcher = workerPattern.matcher(line);
        if (matcher.find()) {
            return matcher.group(1).trim();
        }
        return null;
    }

    /**
     * 提取任务ID
     */
    private String extractTaskId(String line) {
        // 匹配 task:shu-1777 格式
        java.util.regex.Pattern taskPattern = java.util.regex.Pattern.compile(
            "task:([a-zA-Z0-9-]+)"
        );
        java.util.regex.Matcher matcher = taskPattern.matcher(line);
        if (matcher.find()) {
            return matcher.group(1).trim();
        }
        return null;
    }

    /**
     * 提取脚本信息
     */
    private String extractScript(String line) {
        // 匹配 script:iphone:1.9.6 格式
        java.util.regex.Pattern scriptPattern = java.util.regex.Pattern.compile(
            "script:([a-zA-Z0-9:.]+)"
        );
        java.util.regex.Matcher matcher = scriptPattern.matcher(line);
        if (matcher.find()) {
            return matcher.group(1).trim();
        }
        return null;
    }

    /**
     * 验证IP地址格式
     */
    private boolean isValidIpAddress(String ip) {
        if (ip == null || ip.trim().isEmpty()) {
            return false;
        }

        String ipPattern = "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
        return ip.matches(ipPattern);
    }

    /**
     * 连接测试
     * @param authHeader
     * @return
     */
    @GetMapping("/test-connection")
    public R testConnection(
            @RequestHeader(value = "Authorization", required = false) String authHeader) {

        Map<String, Object> response = new HashMap<>();

        try {
            boolean canConnect = sshService.testConnection();
            response.put("success", canConnect);
            response.put("server", sshConfig.getHost());
            response.put("port", sshConfig.getPort());
            response.put("username", sshConfig.getUsername());
            response.put("message", canConnect ? "连接成功" : "连接失败");

            return R.success(AppHttpCodeEnum.SUCCESS)
                    .data(response);

        } catch (Exception e) {
            return R.error(AppHttpCodeEnum.ERROR)
                    .message("连接测试失败");
        }
    }

    /**
     * 检查服务器的连接状态
     * @return
     */
    @GetMapping("/health")
    public R healthCheck() {
        Map<String, Object> response = new HashMap<>();
        response.put("status", "UP");
        response.put("service", "SSH Command Executor");
        response.put("server", sshConfig.getHost());
        response.put("port", sshConfig.getPort());
        response.put("userName", sshConfig.getUsername());
        return R.success(AppHttpCodeEnum.SUCCESS)
                .data(response);
    }


}